package com.xin.libandroidpaysocial.pay.alipay;

import android.app.Activity;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.just.agentweb.AgentWeb;
import com.xin.libandroidpaysocial.R;
import com.xin.libandroidpaysocial.pay.Constants;
import com.xin.libandroidpaysocial.pay.PayEventBusData;
import org.greenrobot.eventbus.EventBus;

/**
 * Created by user on 2017/11/13.
 * 功能描述：支付宝
 * https://docs.open.alipay.com/204/105695/
 * https://tech.open.alipay.com/support/knowledge/index.htm?knowledgeId=201602156692&categoryId=24120#/?_k=p616ot
 */

public class WebViewForAPayActivity extends Activity {
    public static final String ExtraTitle = "ExtraTitle";
    public static final String ExtraUrl = "ExtraUrl";
    LinearLayout layout;
    private AgentWeb mAgentWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_for_alipay);
        initView();
    }

    private void initView() {
        layout=findViewById(R.id.layout);
        setTitle(getIntent().getStringExtra(ExtraTitle));
        AgentWeb.PreAgentWeb ready = AgentWeb.with(this)//传入Activity or Fragment
                .setAgentWebParent(layout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams ,第一个参数和第二个参数应该对应。
                .useDefaultIndicator()// 使用默认进度条
                .setWebViewClient(new MyWebViewClient())
                .createAgentWeb()
                .ready();
        String url = getIntent().getStringExtra(ExtraUrl);
        if (url != null) {
            mAgentWeb = ready.go(url);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        /*https://tech.open.alipay.com/support/knowledge/index.htm?knowledgeId=201602156692&categoryId=24120#/?_k=p616ot*/
        //mAgentWeb.getWebLifeCycle().onPause();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mAgentWeb!=null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAgentWeb!=null) {
            mAgentWeb.getWebLifeCycle().onPause();
            mAgentWeb.getWebLifeCycle().onDestroy();
        }
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            if (!(url.startsWith("http") || url.startsWith("https"))) {
                return true;
            }
            /**
             * 推荐采用的新的二合一接口(payInterceptorWithUrl),只需调用一次
             */
            final PayTask task = new PayTask(WebViewForAPayActivity.this);
            boolean isIntercepted = task.payInterceptorWithUrl(url, true, new AlipayH5PayCallback(view));
            if (!isIntercepted) {
                view.loadUrl(url);
            }
            return true;
        }
    }

    private class AlipayH5PayCallback implements H5PayCallback {
        WebView view;

        public AlipayH5PayCallback(WebView view) {
            this.view = view;
        }

        @Override
        public void onPayResult(H5PayResultModel result) {


            final String url = result.getReturnUrl();
            if (!TextUtils.isEmpty(url)) {
                WebViewForAPayActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        view.loadUrl(url);
                    }
                });
            }
            /*9000——订单支付成功 8000——正在处理中 4000——订单支付失败 5000——重复请求 6001——用户中途取消 6002——网络连接出错*/
            PayEventBusData payResult = new PayEventBusData(1);
            if (TextUtils.equals(result.getResultCode(), "9000")) {
                payResult.setState(0);
                payResult.setMsg(Constants.PaySuccess);
            } else if (TextUtils.equals(result.getResultCode(), "8000")) {
                payResult.setMsg("正在处理中");
            } else if (TextUtils.equals(result.getResultCode(), "4000")) {
                payResult.setMsg("充值失败，请再次重试");
            } else if (TextUtils.equals(result.getResultCode(), "5000")) {
                payResult.setMsg("重复请求");
            } else if (TextUtils.equals(result.getResultCode(), "6001")) {
                payResult.setMsg("用户中途取消");
            } else if (TextUtils.equals(result.getResultCode(), "6002")) {
                payResult.setMsg("网络连接出错");
            }
            EventBus.getDefault().post(payResult);
            finish();


        }
    }
}